import 'package:aio/aio.dart';
import 'package:flutter/material.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/http/bean/wroks/search_bean.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import 'package:app/src/ui/route/helper/route_helper.dart';
import 'package:app/src/utils/status_utils.dart';

import '../../http/bean/user.dart';
import '../../http/bean/worksdo/material_requisition_bean.dart';
import '../../http/bean/wroks/dispatchingaudit_bean.dart';
import '../../http/bean/ywx_limit.dart';
import '../../http/model/config_model.dart';
import '../app_ui.dart';
import '../route/works/public/review_list.dart';

//fixme 判断搜索下拉框是否显示。因为输入法软键盘出现和消失都会自动刷新页面。
//fixme 所以要防止搜索下拉框和一般的弹窗同时出现；防止页面不停的刷新。
bool isShowPopuMenuWithSearch = false;
ValueNotifier<String>? valueNotifierCalss = null; //申请班组数据更新。
showPopuMenuWithSearch(BuildContext context, YwxItem? itemData,
    {GlobalKey? globalKey,
    Offset? offset,
    required SearchInfo searchInfo,
    VoidCallback? onPressed}) {
  var itemHeight = 66.0;
  var itemsHeight = 40.0;
  var items = <Widget>[];
  //审核状态
  if (searchInfo.isShowStatus) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextClick(context, AppStrings.of(context).AuditStatus,
        searchInfo.getStatusOrderType(context), onTap: (valueNotifier) {
      var datas = <RollerBean>[];
      datas.add(RollerBean(
          key: AppStatusUtils.status_1, value: AppStrings.of(context).Status1));
      datas.add(RollerBean(
          key: AppStatusUtils.status_2, value: AppStrings.of(context).Status2));
      if (searchInfo.isShowStatusAll) {
        datas.add(RollerBean(key: null, value: AppStrings.of(context).Status0));
      }
      AppDialog.showDialogWithRollerPicker(context,
              datas: datas, value: valueNotifier.value)
          ?.then((value) {
        if (value != null && value!.value != null) {
          searchInfo.setStatusOrderType(value.key);
          valueNotifier?.value = searchInfo.getStatusOrderType(context); //更新数据
        }
      });
    }));
  }
  //fixme 通用数据搜索条件集合，放在审核状态后面。
  searchInfo.searchDatas?.forEach((element) {
    if (element.isShow) {
      itemsHeight += itemHeight;
      var showName = element.showName ?? "";
      var showValue = element.showValue ?? "";
      if (element.datas != null && element.datas!.length > 0) {
        //fixme 滚轮数据选择
        items.add(_addItemWithTextClick(context, showName ?? "", showValue,
            onTap: (valueNotifier) {
          var datas = element.datas;
          AppDialog.showDialogWithRollerPicker(context,
                  datas: datas, value: valueNotifier.value)
              ?.then((value) {
            if (value != null && value!.value != null) {
              element.data = value;
              element.showValue = value.value;
              valueNotifier?.value = element.showValue ?? ""; //更新数据
            }
          });
        }));
      } else {
        if (element.isTime) {
          //fixme 时间选择类型
          items.add(_addItemWithTextClick(context, showName, showValue,
              onTap: (valueNotifier) {
            AppDialog.showDialogWithDateRangePicker(
                    context: context,
                    start: searchInfo.getInsertStartDatetimeWithDateTime(),
                    end: searchInfo.getInsertEndDatetimeWithDateTime())
                .then((value) {
              element.StartDate = DateTimeUtils.getDateTimeFormat(
                  dateTime: value?.start, dateAndTime: false);
              element.EndDate = DateTimeUtils.getDateTimeFormat(
                  dateTime: value?.end, dateAndTime: false);
              element.showValue = "${element.StartDate}~${element.EndDate}";
              valueNotifier?.value = element.showValue ?? ""; //更新数据
            });
          }));
        } else {
          //fixme 正常文本输入类型。
          items.add(_addItemWithTextField(context, showName, value: showValue,
              onChanged: (value) {
            element.showValue = value;
          }));
        }
      }
    }
  });
  //请购单号
  if (searchInfo.isShowPurchaseOrderNumber) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextField(
        context, AppStrings.of(context).PurchaseOrderNumber,
        value: searchInfo.PurchaseOrderNumber, onChanged: (value) {
      searchInfo.PurchaseOrderNumber = value;
    }));
  }
  //采购单号
  if (searchInfo.isPurOrderCode) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextField(
        context, AppStrings.of(context).PurOrderCode,
        value: searchInfo.PurOrderCode, onChanged: (value) {
      searchInfo.PurOrderCode = value;
    }));
  }
  //采购合同号
  if (searchInfo.isPurContractCode) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextField(
        context, AppStrings.of(context).PurContractCode,
        value: searchInfo.PurContractCode, onChanged: (value) {
      searchInfo.PurContractCode = value;
    }));
  }
  //子合同号
  if (searchInfo.isPurBodyCode) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextField(
        context, AppStrings.of(context).PurBodyCode2,
        value: searchInfo.PurBodyCode, onChanged: (value) {
      searchInfo.PurBodyCode = value;
    }));
  }
  //运输合同号
  if (searchInfo.isLContractCode) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextField(
        context, AppStrings.of(context).LContractCode,
        value: searchInfo.LContractCode, onChanged: (value) {
      searchInfo.LContractCode = value;
    }));
  }
  //合同编号
  if (searchInfo.isShowContractCode) {
    itemsHeight += itemHeight;
    var showName = searchInfo.showContractCodeName;
    if (StringUtils.isEmpty(showName)) {
      showName = AppStrings.of(context).ContractCode;
    }
    items.add(_addItemWithTextField(context, showName!,
        value: searchInfo.ContractCode,
        readOnly: searchInfo.readOnlyWithContractCode, onChanged: (value) {
      searchInfo.ContractCode = value;
    }));
  }
  //合同外部编号
  if (searchInfo.isShowOutCode) {
    itemsHeight += itemHeight;
    var showNmae = searchInfo.ShowOutCodeName;
    if (StringUtils.isEmpty(showNmae)) {
      showNmae = AppStrings.of(context).OutCode;
    }
    items.add(_addItemWithTextField(context, showNmae!,
        value: searchInfo.OutCode, onChanged: (value) {
      searchInfo.OutCode = value;
    }));
  }
  //批次号
  if (searchInfo.isShowPoCode) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextField(context, AppStrings.of(context).PoCode,
        value: searchInfo.PoCode, onChanged: (value) {
      searchInfo.PoCode = value;
    }));
  }
  //订单编号
  if (searchInfo.isShowOrderCode) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextField(context, AppStrings.of(context).OrderCode,
        value: searchInfo.OrderCode, onChanged: (value) {
      searchInfo.OrderCode = value;
    }));
  }
  //订单外部编号
  if (searchInfo.isShowOrderOutCode) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextField(
        context, AppStrings.of(context).OrderOutCode,
        value: searchInfo.OrderOutCode, onChanged: (value) {
      searchInfo.OrderOutCode = value;
    }));
  }
  //通知单号
  if (searchInfo.isShowNoticeId) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextField(context, AppStrings.of(context).NoticeId,
        value: searchInfo.NoticeId, onChanged: (value) {
      searchInfo.NoticeId = value;
    }));
  }
  //fixme 申请单号
  if (searchInfo.isShowApplicationCode) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextField(
        context, AppStrings.of(context).ApplicationCode,
        value: searchInfo.ApplicationCode, onChanged: (value) {
      searchInfo.ApplicationCode = value;
      searchInfo.Applicationcode = value;
    }));
  }
  //fixme 领料单号
  if (searchInfo.isShowPickCode) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextField(context, AppStrings.of(context).PickCode,
        value: searchInfo.PickCode, onChanged: (value) {
      searchInfo.PickCode = value;
      searchInfo.PickCode = value;
    }));
  }
  //fixme 项目名称
  if (searchInfo.isShowProjectName) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextField(context, AppStrings.of(context).ProjectName,
        value: searchInfo.ProjectName, onChanged: (value) {
      searchInfo.ProjectName = value;
      searchInfo.Projectname = value;
    }));
  }
  //fixme 客户名称
  if (searchInfo.isShowCustomerName) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextField(
        context, AppStrings.of(context).CustomerName,
        value: searchInfo.CustomerName, onChanged: (value) {
      searchInfo.CustomerName = value;
      searchInfo.Customername = value;
    }));
  }
  //规格
  if (searchInfo.isShowSize) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextField(
        context, AppStrings.of(context).Specifications, value: searchInfo.Size,
        onChanged: (value) {
      searchInfo.Size = value;
    }));
  }
  //姓名
  if (searchInfo.isShowTheName) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextField(context, AppStrings.of(context).TheName,
        value: searchInfo.TheName, onChanged: (value) {
      searchInfo.TheName = value;
    }));
  }
  //加班时长
  if (searchInfo.isShowOvertimeHours) {
    itemsHeight += itemHeight;
    items.add(
        _addItemWithTextField2(context, AppStrings.of(context).OvertimeHours2,
            value: searchInfo.OvertimeHoursStart,
            onChanged: (value) {
              searchInfo.OvertimeHoursStart = value?.trim();
              // if (StringUtils.isNotEmpty(value)) {
              //   try {
              //     int i = double.parse(value).toInt();
              //     if (StringUtils.isNotEmpty(searchInfo.OvertimeHoursEnd)) {
              //       int i2 = double.parse(searchInfo.OvertimeHoursEnd!).toInt();
              //       if (i > i2) {
              //         //开始时长不能大于结束时长
              //         showDialogWithInfo(context,
              //             content:
              //                 AppStrings.of(context).OvertimeHoursStart2Mes);
              //         return;
              //       }
              //     }
              //     searchInfo.OvertimeHoursStart = i.toString();
              //   } catch (e) {
              //     print("加班时长开始时长输入异常$e");
              //   }
              // } else {
              //   searchInfo.OvertimeHoursStart = "";
              // }
            },
            value2: searchInfo.OvertimeHoursEnd,
            onChanged2: (value) {
              searchInfo.OvertimeHoursEnd = value?.trim();
              // if (StringUtils.isNotEmpty(value)) {
              //   try {
              //     int i = double.parse(value).toInt();
              //     if (StringUtils.isNotEmpty(searchInfo.OvertimeHoursStart)) {
              //       int i2 =
              //           double.parse(searchInfo.OvertimeHoursStart!).toInt();
              //       if (i < i2) {
              //         //结束时长不能小于开始时长
              //         showDialogWithInfo(context,
              //             content: AppStrings.of(context).OvertimeHoursEnd2Mes);
              //         return;
              //       }
              //     }
              //     searchInfo.OvertimeHoursEnd = i.toString();
              //   } catch (e) {
              //     print("加班时长结束时长输入异常$e");
              //   }
              // } else {
              //   searchInfo.OvertimeHoursEnd = "";
              // }
            }));
  }
  //客服经理
  if (searchInfo.isShowMerchandiserName) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextClick(
        context,
        AppStrings.of(context).MerchandiserName,
        searchInfo.MerchandiserName, onTap: (valueNotifier) {
      searchInfo.getManagergetlistWith03(context, (value) {
        var datas = <RollerBean>[];
        value?.forEach((element) {
          datas.add(
              RollerBean(key: element.PersonId, value: element.PersonName));
        });
        // datas.add(RollerBean(key: '1', value: '陆清波'));
        // datas.add(RollerBean(key: '2', value: '朱高怀'));
        // datas.add(RollerBean(key: '3', value: '叶勇'));
        // datas.add(RollerBean(key: '1', value: '黄定锋'));
        showDialogWithRollerPicker(context,
                datas: datas, value: valueNotifier.value)
            ?.then((value) {
          if (value != null && value!.value != null) {
            searchInfo.MerchandiserName = value.value;
            searchInfo.Merchandisername = value.value;
            valueNotifier?.value = value!.value!; //更新数据
          }
        });
      });
    }));
  }
  //销售经理
  if (searchInfo.isShowSalesmanName) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextClick(
        context, AppStrings.of(context).SalesmanName, searchInfo.SalesmanName,
        onTap: (valueNotifier) {
      searchInfo.getManagergetlistWith02(context, (value) {
        var datas = <RollerBean>[];
        value?.forEach((element) {
          datas.add(
              RollerBean(key: element.PersonId, value: element.PersonName));
        });
        // datas.add(RollerBean(key: '1', value: '王贤明'));
        // datas.add(RollerBean(key: '1', value: '陆清波'));
        // datas.add(RollerBean(key: '2', value: '朱高怀'));
        // datas.add(RollerBean(key: '3', value: '叶勇'));
        // datas.add(RollerBean(key: '1', value: '黄定锋'));
        AppDialog.showDialogWithRollerPicker(context,
                datas: datas, value: valueNotifier.value)
            ?.then((value) {
          if (value != null && value!.value != null) {
            searchInfo.SalesmanName = value.value;
            searchInfo.Salesmanname = value.value;
            valueNotifier?.value = value!.value!; //更新数据
          }
        });
      });
    }));
  }
  //fixme 所属工厂
  if (searchInfo.isShowFactory) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextClick(
        context,
        AppStrings.of(context).FactoryOfOwnership,
        searchInfo.factory?.FactoryName, onTap: (valueNotifier) {
      ConfigModel.getFactorygetlist(context, false, (value) {
        if (value != null && value!.isSuccessForData()) {
          AppDialog.showDialogWithRollerPicker(context,
                  datas: value.Data, data: searchInfo.factory)
              ?.then((value) {
            if (value != null) {
              searchInfo.factory = value;
              valueNotifier?.value = value!.value!; //更新数据
            }
          });
        }
      });
    }));
  }
  //物料名称
  if (searchInfo.isShowMaterialName) {
    itemsHeight += itemHeight;
    var showName = searchInfo.PreMaterialName;
    if (StringUtils.isEmpty(showName)) {
      showName = AppStrings.of(context).MaterialName3; //物料名称
    }
    items.add(_addItemWithTextField(context, showName!,
        value: searchInfo.MaterialName, onChanged: (value) {
      searchInfo.MaterialName = value;
    }));
  }
  //fixme 物料类型：原片，辅料，五金
  if (searchInfo.isShowTypeOfMaterial) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextClick(
        context,
        AppStrings.of(context).TypeOfMaterial,
        searchInfo.TypeOfMaterial?.Name, onTap: (valueNotifier) {
      var datas = searchInfo.getListTypeOfMaterial(context);
      AppDialog.showDialogWithRollerPicker(context,
              datas: datas, value: valueNotifier.value)
          ?.then((value) {
        if (value != null && value!.value != null) {
          searchInfo.TypeOfMaterial = value;
          searchInfo.MaterialType = value?.key;
          valueNotifier?.value = value!.value!; //更新数据
        }
      });
    }));
  }
  //fixme 种类，如：原片种类
  if (searchInfo.isShowSpecies) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextClick(
        context, searchInfo.SpeciesName, searchInfo.Species?.Name,
        onTap: (valueNotifier) {
      PreSearchMaterialInfo data = PreSearchMaterialInfo();
      data.type = PreSearchMaterialInfo.Type_MaterialType;
      data.MaterialType = PurDemand.getMaterialTypeWith(itemData?.ReviewType2);
      searchInfo.getOtherWorkApply2(context, data, (value) {
        var datas = <RollerBean>[];
        value?.forEach((element) {
          datas.add(RollerBean(key: element.Id, value: element.Name));
        });
        AppDialog.showDialogWithRollerPicker(context,
                datas: datas, value: valueNotifier.value)
            ?.then((value) {
          if (value != null && value!.value != null) {
            if (searchInfo.Species == null) {
              searchInfo.Species = OtherWorkApply();
            }
            searchInfo.Species?.Id = value.key;
            searchInfo.Species?.Name = value.value;
            valueNotifier?.value = value!.value!; //更新数据
          }
        });
      });
    }));
  }
  //fixme 品牌，如：原片品牌
  if (searchInfo.isShowBrand) {
    itemsHeight += itemHeight;
    var showname = searchInfo.BrandName;
    if (StringUtils.isEmpty(showname)) {
      showname = AppStrings.of(context).Brand;
    }
    items.add(_addItemWithTextClick(context, showname, searchInfo.Brand?.Name,
        onTap: (valueNotifier) {
      PreSearchMaterialInfo data = PreSearchMaterialInfo();
      data.type =
          PreSearchMaterialInfo.getTypeWithManufacturer(itemData?.ReviewType2);
      data.MaterialType = PurDemand.getMaterialTypeWith(itemData?.ReviewType2);
      searchInfo.getOtherWorkApply2(context, data, (value) {
        var datas = <RollerBean>[];
        value?.forEach((element) {
          datas.add(RollerBean(key: element.Id, value: element.Name));
        });
        AppDialog.showDialogWithRollerPicker(context,
                datas: datas, value: valueNotifier.value)
            ?.then((value) {
          if (value != null && value!.value != null) {
            if (searchInfo.Brand == null) {
              searchInfo.Brand = OtherWorkApply();
            }
            searchInfo.Brand?.Id = value.key;
            searchInfo.ManufacturerId = value.key;
            searchInfo.Brand?.Name = value.value;
            valueNotifier?.value = value!.value!; //更新数据
          }
        });
      });
    }));
  }
  //fixme 供应商
  if (searchInfo.isShowSupplier) {
    itemsHeight += itemHeight;
    var showname = AppStrings.of(context).SupplierName;
    items.add(_addItemWithTextClick(context, showname, searchInfo.SupplierName,
        onTap: (valueNotifier) {
      PreSearchMaterialInfo data = PreSearchMaterialInfo();
      data.type = "GetSupplierDDL";
      searchInfo.getOtherWorkApply2(context, data, (value) {
        var datas = <RollerBean>[];
        value?.forEach((element) {
          datas.add(RollerBean(key: element.Id, value: element.Name));
        });
        AppDialog.showDialogWithRollerPicker(context,
                datas: datas, value: valueNotifier.value)
            ?.then((value) {
          if (value != null && value!.value != null) {
            searchInfo.SupplierId = value.key;
            searchInfo.SupplierName = value.value;
            valueNotifier?.value = value!.value!; //更新数据
          }
        });
      });
    }));
  }
  //fixme 承运商
  if (searchInfo.isCarrier) {
    itemsHeight += itemHeight;
    var showname = AppStrings.of(context).CarrierName;
    items.add(_addItemWithTextClick(context, showname, searchInfo.CarrierName,
        onTap: (valueNotifier) {
      PreSearchMaterialInfo data = PreSearchMaterialInfo();
      data.type = "GetCarriersDDL";
      searchInfo.getOtherWorkApply2(context, data, (value) {
        var datas = <RollerBean>[];
        value?.forEach((element) {
          datas.add(RollerBean(key: element.Id, value: element.Name));
        });
        AppDialog.showDialogWithRollerPicker(context,
                datas: datas, value: valueNotifier.value)
            ?.then((value) {
          if (value != null && value!.value != null) {
            searchInfo.CarrierId = value.key;
            searchInfo.CarrierName = value.value;
            valueNotifier?.value = value!.value!; //更新数据
          }
        });
      });
    }));
  }
  //fixme 采购员
  if (searchInfo.isCreater) {
    itemsHeight += itemHeight;
    var showname = AppStrings.of(context).PersonName7;
    items.add(_addItemWithTextClick(context, showname, searchInfo.CreaterName,
        onTap: (valueNotifier) {
      PreSearchMaterialInfo data = PreSearchMaterialInfo();
      data.type = "GetPurchaserDDL";
      searchInfo.getOtherWorkApply2(context, data, (value) {
        var datas = <RollerBean>[];
        value?.forEach((element) {
          datas.add(RollerBean(key: element.Id, value: element.Name));
        });
        AppDialog.showDialogWithRollerPicker(context,
                datas: datas, value: valueNotifier.value)
            ?.then((value) {
          if (value != null && value!.value != null) {
            searchInfo.Creater = value.key;
            searchInfo.CreaterName = value.value;
            valueNotifier?.value = value!.value!; //更新数据
          }
        });
      });
    }));
  }
  //创建人
  if (searchInfo.isShowFounder) {
    if (searchInfo.isLContract) {
      //运输合同里的创建人
      itemsHeight += itemHeight;
      var showname = AppStrings.of(context).Founder;
      items.add(_addItemWithTextClick(context, showname, searchInfo.FounderName,
          onTap: (valueNotifier) {
        PreSearchMaterialInfo data = PreSearchMaterialInfo();
        data.type = "GetCreaterTable";
        searchInfo.getOtherWorkApply2(context, data, (value) {
          var datas = <RollerBean>[];
          value?.forEach((element) {
            datas.add(RollerBean(key: element.Id, value: element.Name));
          });
          AppDialog.showDialogWithRollerPicker(context,
                  datas: datas, value: valueNotifier.value)
              ?.then((value) {
            if (value != null && value!.value != null) {
              searchInfo.FounderId = value.key;
              searchInfo.FounderName = value.value;
              valueNotifier?.value = value!.value!; //更新数据
            }
          });
        });
      }));
    } else {
      ///通用创建人
      itemsHeight += itemHeight;
      items.add(_addItemWithTextClick(
          context, AppStrings.of(context).Founder, searchInfo.FounderName,
          onTap: (valueNotifier) {
        PreSearchMaterialInfo data = PreSearchMaterialInfo();
        data.type = PreSearchMaterialInfo.Type_Creater;
        data.MaterialType =
            PurDemand.getMaterialTypeWith(itemData?.ReviewType2);
        searchInfo.getOtherWorkApply2(context, data, (value) {
          var datas = <RollerBean>[];
          value?.forEach((element) {
            datas.add(RollerBean(key: element.Id, value: element.Name));
          });
          // datas.add(RollerBean(key: '1', value: '王贤明'));
          // datas.add(RollerBean(key: '1', value: '陆清波'));
          // datas.add(RollerBean(key: '2', value: '朱高怀'));
          // datas.add(RollerBean(key: '3', value: '叶勇'));
          // datas.add(RollerBean(key: '1', value: '黄定锋'));
          String? defaultValue = valueNotifier.value;
          if (StringUtils.isEmpty(searchInfo.FounderId)) {
            defaultValue = null;
          }
          AppDialog.showDialogWithRollerPicker(context,
                  datas: datas, value: defaultValue)
              ?.then((value) {
            if (value != null && value!.value != null) {
              searchInfo.FounderId = value.key;
              searchInfo.FounderName = value.value;
              valueNotifier?.value = value!.value!; //更新数据
            }
          });
        });
      }));
    }
  }
  //fixme 部门
  if (searchInfo.isShowDept) {
    itemsHeight += itemHeight;
    var showname = AppStrings.of(context).department;
    items.add(_addItemWithTextClick(context, showname, searchInfo.DeptName,
        onTap: (valueNotifier) {
      searchInfo.getdepartment(context, (value) {
        var datas = value;
        var department = Department();
        department.DeptName = "";
        department.DeptId = "";
        department.key = "";
        department.value = "";
        datas.insert(0, department); //第一位插入一个空值
        // datas.add(RollerBean(key: '1', value: '陆清波'));
        // datas.add(RollerBean(key: '2', value: '朱高怀'));
        // datas.add(RollerBean(key: '3', value: '叶勇'));
        // datas.add(RollerBean(key: '1', value: '黄定锋'));
        AppDialog.showDialogWithRollerPicker(context,
                datas: datas, value: valueNotifier.value)
            ?.then((value) {
          if (value != null && value!.value != null) {
            searchInfo.DeptId = value.key ?? "";
            searchInfo.DeptName = value.value ?? "";
            valueNotifier?.value = value!.value!; //更新数据
          }
        });
      });
    }));
  }
  //申请人
  if (searchInfo.isShowUserPerson) {
    itemsHeight += itemHeight;
    var _name = AppStrings.of(context).ApplyName; //申请人
    if (StringUtils.isNotEmpty(searchInfo.showUserPerson)) {
      _name = searchInfo?.showUserPerson ?? "";
    }
    if (searchInfo.isEnableInputUserPerson) {
      //允许手动输入。
      items.add(_addItemWithTextFieldClick(
          context, _name, searchInfo.UserPerson?.PersonName ?? "",
          onChanged: (value) {
        if (searchInfo.UserPerson == null) {
          searchInfo.UserPerson = UserApplicant();
        }
        searchInfo.UserPerson?.PersonName = value;
        searchInfo.UserPerson?.PersonCode = "";
        searchInfo.UserPerson?.PersonId = "";
        searchInfo.UserPerson?.DeptName = "";
      }, onTap: (valueNotifier) {
        AppRouteHelper.goSearchApplyNameRoute(context, (value) {
          if (value != null && value is UserApplicant) {
            valueNotifier?.value = value!.value!; //更新数据
            searchInfo.UserPerson = value;
          }
        });
      }));
    } else {
      items.add(_addItemWithTextClick(
          context, _name, searchInfo.UserPerson?.PersonName ?? "",
          onTap: (valueNotifier) {
        AppRouteHelper.goSearchApplyNameRoute(context, (value) {
          if (value != null && value is UserApplicant) {
            valueNotifier?.value = value!.value!; //更新数据
            searchInfo.UserPerson = value;
          }
        });
      }));
    }
  }
  //fixme 状态(采购状态)
  if (searchInfo.isShowPurchaseStatus) {
    itemsHeight += itemHeight;
    String? showName = searchInfo.showPurchaseStatusName;
    if (StringUtils.isEmpty(showName)) {
      showName = AppStrings.of(context).State;
    }
    items.add(_addItemWithTextClick(
        context, showName!, searchInfo.PurchaseStatus?.Name,
        onTap: (valueNotifier) {
      var datas = searchInfo.getListPurchaseStatus(context);
      AppDialog.showDialogWithRollerPicker(context,
              datas: datas, value: valueNotifier.value)
          ?.then((value) {
        if (value != null && value!.value != null) {
          searchInfo.PurchaseStatus = value;
          //searchInfo.Status = value.key;
          searchInfo.DocumentStatus = value.key;
          valueNotifier?.value = value!.value!; //更新数据
        }
      });
    }));
  }
  //fixme 所属工序
  if (searchInfo.isShowProcessName) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextClick(
        context, AppStrings.of(context).ProcessName3, searchInfo.ProcessName,
        onTap: (valueNotifier) {
      searchInfo.getOtherWorkApply(context, (value) {
        var datas = <RollerBean>[];
        value?.forEach((element) {
          datas.add(RollerBean(key: element.Id, value: element.Name));
        });
        // datas.add(RollerBean(key: '1', value: '王贤明'));
        // datas.add(RollerBean(key: '1', value: '陆清波'));
        // datas.add(RollerBean(key: '2', value: '朱高怀'));
        // datas.add(RollerBean(key: '3', value: '叶勇'));
        // datas.add(RollerBean(key: '1', value: '黄定锋'));
        AppDialog.showDialogWithRollerPicker(context,
                datas: datas, value: valueNotifier.value)
            ?.then((value) {
          if (value != null && value!.value != null) {
            if (searchInfo.ProcessId != value.key) {
              //fixme 工序选中发生变化。班组要重新置空。
              searchInfo.ApplicationClassName = null;
              searchInfo.ApplicationClassId = null;
              searchInfo.ApplicationClass = null;
              //班组数据更新
              valueNotifierCalss?.value = "";
            }
            searchInfo.ProcessName = value.value;
            searchInfo.ProcessId = value.key;
            valueNotifier?.value = value!.value!; //更新数据
          }
        });
      });
    }));
  }
  //fixme 申请班组
  if (searchInfo.isShowApplicationClassName) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextClick(context, AppStrings.of(context).ApplyTeam,
        searchInfo.ApplicationClassName, mValueNotifier: (valueNotifier) {
      valueNotifierCalss = valueNotifier; //班组选择；根据工序选择要实时更新。
    }, onTap: (valueNotifier) {
      valueNotifierCalss = valueNotifier;
      searchInfo.getOtherWorkApplyWitHClass(context, (value) {
        var datas = <RollerBean>[];
        value?.forEach((element) {
          datas.add(RollerBean(key: element.Id, value: element.Name));
        });
        // datas.add(RollerBean(key: '1', value: '王贤明'));
        // datas.add(RollerBean(key: '1', value: '陆清波'));
        // datas.add(RollerBean(key: '2', value: '朱高怀'));
        // datas.add(RollerBean(key: '3', value: '叶勇'));
        // datas.add(RollerBean(key: '1', value: '黄定锋'));
        AppDialog.showDialogWithRollerPicker(context,
                datas: datas, value: valueNotifier.value)
            ?.then((value) {
          if (value != null && value!.value != null) {
            searchInfo.ApplicationClassName = value.value;
            searchInfo.ApplicationClassId = value.key;
            valueNotifier?.value = value!.value!; //更新数据
          }
        });
      });
    }));
  }
  //我的工单：设备编码
  if (searchInfo.isShowDeviceCoding) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextField(
        context, AppStrings.of(context).Devicecoding,
        value: searchInfo.DeviceCoding, onChanged: (value) {
      searchInfo.DeviceCoding = value;
    }));
  }
  //我的单号：五金领用状态
  if (searchInfo.isShowReceivingStatus) {
    itemsHeight += itemHeight;
    items.add(_addItemWithTextClick(
        context, AppStrings.of(context).State, searchInfo.ReceivingStatusValue,
        onTap: (valueNotifier) {
      var datas = searchInfo.getReceivingStatusDatas(context);
      AppDialog.showDialogWithRollerPicker(context,
              datas: datas, value: valueNotifier.value)
          ?.then((value) {
        if (value != null && value!.value != null) {
          searchInfo.ReceivingStatusKey = value?.key;
          searchInfo.ReceivingStatusValue = value?.value;
          valueNotifier?.value = value!.value!; //更新数据
        }
      });
    }));
  }

  //采购申请日期
  if (searchInfo.isShowPurStartDate) {
    itemsHeight += itemHeight;
    String _name = AppStrings.of(context).PurStartDate; //采购申请日期
    // if (StringUtils.isNotEmpty(searchInfo.showAddTime)) {
    //   _name = searchInfo.showAddTime ?? _name; //如：外车运费审核显示：上报日期
    // }
    items.add(_addItemWithTextClick(
        context, _name, searchInfo.getPurStartDate(), onTap: (valueNotifier) {
      AppDialog.showDialogWithDateRangePicker(
              context: context,
              start: searchInfo.getInsertStartDatetimeWithDateTime(),
              end: searchInfo.getInsertEndDatetimeWithDateTime())
          .then((value) {
        searchInfo.BPurStartDate = DateTimeUtils.getDateTimeFormat(
            dateTime: value?.start, dateAndTime: false);
        searchInfo.EPurStartDate = DateTimeUtils.getDateTimeFormat(
            dateTime: value?.end, dateAndTime: false);
        ;
        valueNotifier?.value = searchInfo.getPurStartDate(); //更新数据
      });
    }));
  }
  //采购要货日期
  if (searchInfo.isShowPurEndDate) {
    itemsHeight += itemHeight;
    String _name = AppStrings.of(context).PurEndDate; //采购要货日期
    // if (StringUtils.isNotEmpty(searchInfo.showAddTime)) {
    //   _name = searchInfo.showAddTime ?? _name; //如：外车运费审核显示：上报日期
    // }
    items.add(_addItemWithTextClick(context, _name, searchInfo.getPurEndDate(),
        onTap: (valueNotifier) {
      AppDialog.showDialogWithDateRangePicker(
              context: context,
              start: searchInfo.getInsertStartDatetimeWithDateTime(),
              end: searchInfo.getInsertEndDatetimeWithDateTime())
          .then((value) {
        searchInfo.BPurEndDate = DateTimeUtils.getDateTimeFormat(
            dateTime: value?.start, dateAndTime: false);
        searchInfo.EPurEndDate = DateTimeUtils.getDateTimeFormat(
            dateTime: value?.end, dateAndTime: false);
        valueNotifier?.value = searchInfo.getPurEndDate(); //更新数据
      });
    }));
  }
  //签订日期
  if (searchInfo.isShowSignSDateTime) {
    itemsHeight += itemHeight;
    String _name = AppStrings.of(context).SignDate; //签订日期
    // if (StringUtils.isNotEmpty(searchInfo.showAddTime)) {
    //   _name = searchInfo.showAddTime ?? _name; //如：外车运费审核显示：上报日期
    // }
    items.add(_addItemWithTextClick(
        context, _name, searchInfo.getSignDateTime(), onTap: (valueNotifier) {
      AppDialog.showDialogWithDateRangePicker(
              context: context,
              start: searchInfo.getInsertStartDatetimeWithDateTime(),
              end: searchInfo.getInsertEndDatetimeWithDateTime())
          .then((value) {
        searchInfo.SignSDateTime = DateTimeUtils.getDateTimeFormat(
            dateTime: value?.start, dateAndTime: false);
        searchInfo.SignEDateTime = DateTimeUtils.getDateTimeFormat(
            dateTime: value?.end, dateAndTime: false);
        ;
        valueNotifier?.value = searchInfo.getSignDateTime(); //更新数据
      });
    }));
  }
  //添加时间，改成申请日期
  if (searchInfo.isShowAddTime) {
    itemsHeight += itemHeight;
    String _name = AppStrings.of(context).AddDate5; //申请日期
    if (StringUtils.isNotEmpty(searchInfo.showAddTime)) {
      _name = searchInfo.showAddTime ?? _name; //如：外车运费审核显示：上报日期
    }
    items.add(_addItemWithTextClick(context, _name, searchInfo.getAddTime(),
        onTap: (valueNotifier) {
      AppDialog.showDialogWithDateRangePicker(
              context: context,
              start: searchInfo.getInsertStartDatetimeWithDateTime(),
              end: searchInfo.getInsertEndDatetimeWithDateTime())
          .then((value) {
        searchInfo.InsertStartDatetime = DateTimeUtils.getDateTimeFormat(
            dateTime: value?.start, dateAndTime: false);
        searchInfo.InsertEndDatetime = DateTimeUtils.getDateTimeFormat(
            dateTime: value?.end, dateAndTime: false);
        valueNotifier?.value = searchInfo.getAddTime(); //更新数据
      });
    }));
  }
  //搜索按钮
  items.add(_addItemWithBtn(context, onPressed: () {
    AppRouteHelper.pop(context); //关闭popuWindow(和关闭普通路由是一样的。)
    isShowPopuMenuWithSearch = false;
    ReviewList.setWindowRefresh(); //fixme 列表刷新。
    onPressed?.call(); //点击回调
  }));
  var child = Container(
    height: itemsHeight,
    child: Column(
      children: items,
    ),
  );
  //fixme 这里showPopuWindow是通过路由Route来实现，按返回键时会自动消失。(点击空白区域也会自动消失)
  //fixme globalKey 和 offset 两个都可以指定popuWindow的位置。
  //下拉框PopuWindow
  showPopuWindowWithDrop<String>(
      context: context,
      child: Container(
        child: child,
      ),
      globalKey: globalKey,
      offset: offset,
      onWindowShow: () {
        isShowPopuMenuWithSearch = true;
        // print(
        //     '=================================================================popuwindow显示');
      },
      onWindowDismiss: () {
        isShowPopuMenuWithSearch = false;
        // print(
        //     '=================================================================popuwindow关闭');
        onPressed
            ?.call(); //点击回调;fixme 这里下拉框关闭时，也回调一下；防止用户没有点击搜索按钮，页面搜索条件布局不刷新问题。
      },
      onWindowResponse: (value) {
        isShowPopuMenuWithSearch = false;
        //返回值不为空时，会回调。这里的返回值，就是我们指定的泛型。
        //在onWindowDismiss的后面回调，即：最后回调。
        // print(
        //     '=================================================================popuwindow返回值:${value}');
      });
}

testShowWindow(BuildContext context, GlobalKey? key) {
  Widget widget = Material(
    child: Text('Hello'),
  );
  var position = getWidgetGlobalRelativeRect(key);
  showWindow(
      context: context,
      position: position,
      windowBuilder: (BuildContext context, Animation<double> animation,
          Animation<double> secondaryAnimation) {
        return widget;
      });
  // showWindow<T>(
  //     context: context,
  //     position: position, /// RelativeRect
  //     duration: widget.duration,
  //     windowBuilder: widget.windowBuilder,
  //     onWindowShow: widget.onWindowShow,
  //     onWindowDismiss: widget.onWindowDismiss);
}

///文本输入框
///title 文本标题
///value 文本输入框的值
///onChanged 文本输入框值变化
Widget _addItemWithTextField(BuildContext context, String title,
    {String? value, bool readOnly = false, ValueChanged<String>? onChanged}) {
  var text = Text(
    title,
    style: AppStyle.textStyleWithPopuItem(),
  );
  var textField = TextField(
    controller: TextUtils.setTextEditingController(text: value),
    style: AppStyle.textStyleWithPopuItem(),
    decoration: InputDecoration(
      hintText: AppStrings.of(context).EnterInformation, //'请输入信息'
      border: InputBorder.none,
      contentPadding: EdgeInsets.zero,
    ),
    readOnly: readOnly,
    onChanged: (value) {
      onChanged?.call(value);
    },
  );
  var row = Row(
    children: [
      Expanded(
          child: Padding(
        padding: EdgeInsets.only(left: 16),
        child: text,
      )),
      Expanded(
        child: textField,
        flex: 2,
      )
    ],
  );
  return Material(
    color: Colors.white,
    child: Container(
      height: 46,
      child: Column(
        children: [
          Expanded(child: row),
          Divider(
            height: 1,
            thickness: 1,
            color: AppColors.lineColorWithGrey,
            indent: 16,
            endIndent: 16,
          )
        ],
      ),
    ),
  );
}

///fixme 有两个文本输入框
///title 文本标题
///value 文本输入框的值
///onChanged 文本输入框值变化
Widget _addItemWithTextField2(BuildContext context, String title,
    {String? value,
    ValueChanged<String>? onChanged,
    String? value2,
    ValueChanged<String>? onChanged2}) {
  var text = Text(
    title,
    style: AppStyle.textStyleWithPopuItem(),
  );
  var textField = TextField(
    controller: TextUtils.setTextEditingController(text: value),
    style: AppStyle.textStyleWithPopuItem(),
    decoration: InputDecoration(
      hintText: AppStrings.of(context).OvertimeHoursStart, //开始时长
      border: InputBorder.none,
      contentPadding: EdgeInsets.zero,
    ),
    inputFormatters: [DecimalFormatter(isNegative: false)],
    keyboardType: TextInputType.number,
    onChanged: (value) {
      onChanged?.call(value);
    },
  );
  var textField2 = TextField(
    controller: TextUtils.setTextEditingController(text: value2),
    style: AppStyle.textStyleWithPopuItem(),
    decoration: InputDecoration(
      hintText: AppStrings.of(context).OvertimeHoursEnd, //结束时长
      border: InputBorder.none,
      contentPadding: EdgeInsets.zero,
    ),
    inputFormatters: [DecimalFormatter(isNegative: false)],
    keyboardType: TextInputType.number,
    onChanged: (value) {
      onChanged2?.call(value);
    },
  );
  var row = Row(
    children: [
      Expanded(
          child: Padding(
            padding: EdgeInsets.only(left: 16),
            child: text,
          ),
          flex: 3),
      Expanded(
        child: textField,
        flex: 2,
      ),
      Expanded(
        child: Center(
          child: Text("~"),
        ),
        flex: 1,
      ),
      Expanded(
        child: textField2,
        flex: 3,
      ),
      // Expanded(
      //   child: AppUi.getEmptyView(),
      //   flex: 2,
      // ),
    ],
  );
  return Material(
    color: Colors.white,
    child: Container(
      height: 46,
      child: Column(
        children: [
          Expanded(child: row),
          Divider(
            height: 1,
            thickness: 1,
            color: AppColors.lineColorWithGrey,
            indent: 16,
            endIndent: 16,
          )
        ],
      ),
    ),
  );
}

typedef ResponseCallbackWithValueNotifier = void Function(
    ValueNotifier<String>? valueNotifier);

///点击选择
Widget _addItemWithTextClick(
    BuildContext context, String leftText, String? rightText,
    {ResponseCallbackWithT<ValueNotifier<String>>? onTap,
    ResponseCallbackWithValueNotifier? mValueNotifier = null}) {
  var textLeft = Text(
    leftText,
    style: AppStyle.textStyleWithPopuItem(),
  );
  ValueNotifier<String> valueNotifier = ValueNotifier(rightText ?? "");
  mValueNotifier?.call(valueNotifier);
  var textRight = ValueListenableBuilder(
    valueListenable: valueNotifier,
    builder: ((context, value, child) {
      return Text(value?.toString() ?? "");
    }),
  );
  // var textRight = Text(
  //   rightText,
  //   style: AppStyle.textStyleWithPopuItem(),
  // );
  var row = Row(
    children: [
      Expanded(
          child: Padding(
        padding: EdgeInsets.only(left: 16, top: 8, bottom: 8),
        child: textLeft,
      )),
      Expanded(
        child: Row(
          children: [
            Expanded(
              child: textRight,
            ),
            AppUi.getRightGo(padding: EdgeInsets.only(right: 16))
          ],
        ),
        flex: 2,
      )
    ],
  );
  return Material(
    color: Colors.white,
    child: Container(
      height: 42,
      child: Column(
        children: [
          Expanded(
              child: InkWell(
                  child: row,
                  onTap: () {
                    onTap?.call(valueNotifier);
                  })),
          Divider(
            height: 1,
            thickness: 1,
            color: AppColors.lineColorWithGrey,
            indent: 16,
            endIndent: 16,
          )
        ],
      ),
    ),
  );
}

///文本+点击选择
Widget _addItemWithTextFieldClick(
    BuildContext context, String leftText, String? rightText,
    {ValueChanged<String>? onChanged,
    ResponseCallbackWithT<ValueNotifier<String>>? onTap,
    ResponseCallbackWithValueNotifier? mValueNotifier = null}) {
  var textLeft = Text(
    leftText,
    style: AppStyle.textStyleWithPopuItem(),
  );
  ValueNotifier<String> valueNotifier = ValueNotifier(rightText ?? "");
  mValueNotifier?.call(valueNotifier);
  var textRight = ValueListenableBuilder(
    valueListenable: valueNotifier,
    builder: ((context, value, child) {
      //return Text(value?.toString() ?? "");
      return TextField(
        controller:
            TextUtils.setTextEditingController(text: value?.toString() ?? ""),
        style: AppStyle.textStyleWithPopuItem(),
        decoration: InputDecoration(
          hintText: AppStrings.of(context).EnterInformation, //'请输入信息'
          border: InputBorder.none,
          contentPadding: EdgeInsets.zero,
        ),
        readOnly: false,
        onChanged: (value) {
          onChanged?.call(value);
        },
      );
    }),
  );
  // var textRight = Text(
  //   rightText,
  //   style: AppStyle.textStyleWithPopuItem(),
  // );
  var row = Row(
    children: [
      Expanded(
          child: Padding(
        padding: EdgeInsets.only(left: 16, top: 8, bottom: 8),
        child: textLeft,
      )),
      Expanded(
        child: Row(
          children: [
            Expanded(
              child: textRight,
            ),
            InkWell(
                child: Row(
                  children: [
                    Text(
                      AppStrings.of(context).ClickSelect, //点击选择
                      style: TextStyle(color: Colors.blue),
                    ),
                    AppUi.getRightGo(padding: EdgeInsets.only(right: 16))
                  ],
                ),
                onTap: () {
                  onTap?.call(valueNotifier);
                })
          ],
        ),
        flex: 2,
      )
    ],
  );
  return Material(
    color: Colors.white,
    child: Container(
      height: 42,
      child: Column(
        children: [
          Expanded(child: row),
          Divider(
            height: 1,
            thickness: 1,
            color: AppColors.lineColorWithGrey,
            indent: 16,
            endIndent: 16,
          )
        ],
      ),
    ),
  );
}

///搜索点击按钮
Widget _addItemWithBtn(BuildContext context, {VoidCallback? onPressed}) {
  var button = Center(
    child: Container(
      height: 48,
      child: MaterialButton(
        height: 48,
        minWidth: px.screenWidth(),
        onPressed: () {
          onPressed?.call();
        },
        //label 右边控件（一般为文本），不能为空
        color: ColorUtils.parseColor('#5484ED'),
        //color 按钮颜色
        splashColor: Colors.black12,
        //splashColor 点击时，飞溅扩散的颜色
        //highlightColor: Colors.red, //highlightColor 点击时按钮颜色
        colorBrightness: Brightness.light,
        //colorBrightness 按钮亮度；Brightness.dark 暗系风格;Brightness.light 高亮(默认)
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(10))),
        //shape 形状
        textColor: Colors.white,
        //文本默认颜色
        child: Text(
          AppStrings.of(context).search,
          style: AppStyle.textStyleWithButton(),
        ), //fixme 子控件
      ),
    ),
  );
  return Material(
    color: Colors.white,
    child: Padding(
      child: button,
      padding: EdgeInsets.only(left: 16, right: 16, bottom: 8, top: 8),
    ),
  );
}
